package lex.dm.ui.results;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.table.AbstractTableModel;

public class ResultSetTableModel extends AbstractTableModel
{
	private ResultSet rs = null;
	private List<Object[]> data = new ArrayList<Object[]>();
	private int columnCount = 0;
	private String[] columnNames = {};

	public ResultSetTableModel()
	{}

	public void setResultSet( ResultSet rs ) throws SQLException
	{
		this.clear();
		this.rs = rs;
		ResultSetMetaData rsmd = rs.getMetaData();
		columnCount = rsmd.getColumnCount();
		this.columnNames = new String[columnCount];
		for( int i = 0; i < columnCount; i++ )
			columnNames[i] = rsmd.getColumnLabel( i + 1 );
		while( rs.next() )
		{
			Object[] row = new Object[columnCount];
			for( int i = 0; i < columnCount; i++ )
				row[i] = rs.getObject( i + 1 );
			data.add( row );
		}
		// this.fireTableStructureChanged();
	}

	private void clear()
	{
		if( null != this.rs )
			try
			{
				this.rs.close();
			}
			catch( SQLException e )
			{
				e.printStackTrace();
			}
		data.clear();
		columnCount=0;
		columnNames=new String[0];
	}

	@Override
	public String getColumnName( int column )
	{
		return columnNames[column];
	}

	public int getColumnCount()
	{
		return columnCount;
	}

	public int getRowCount()
	{
		return data.size();
	}

	public Object getValueAt( int row, int column )
	{
		return data.get( row )[column];
	}

	public String toString()
	{
		return this.getRowCount() + "x" + this.getColumnCount();
	}
}
